package com.numberone.iotplatform;

import com.numberone.iotplatform.entity.ERole;
import com.numberone.iotplatform.entity.Role;
import com.numberone.iotplatform.entity.User;
import com.numberone.iotplatform.repository.RoleRepository;
import com.numberone.iotplatform.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 应用主类，包含 CommandLineRunner 用于初始化角色和管理员账户。
 * 所有代码已确认兼容 JDK 1.8。
 */
@SpringBootApplication
@EnableAsync
public class IotPlatformApplication {

    private static final Logger log = LoggerFactory.getLogger(IotPlatformApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(IotPlatformApplication.class, args);
    }

    /**
     * 初始化角色和默认管理员账户。
     * @param roleRepository Role 数据访问仓库
     * @param userRepository User 数据访问仓库
     * @param passwordEncoder 用于密码加密的 Bean
     * @param adminPassword 默认管理员密码（从配置文件读取）
     * @return CommandLineRunner Bean
     */
    @Bean
    CommandLineRunner run(RoleRepository roleRepository, UserRepository userRepository, PasswordEncoder passwordEncoder,
                          @Value("${admin.password:123456}") String adminPassword) {
        return args -> {
            // --- 1. 初始化角色 ---
            Arrays.stream(ERole.values()).forEach(roleEnum -> {
                List<Role> roles = roleRepository.findByName(roleEnum);
                if (roles.isEmpty()) {
                    log.info("Creating role: {}", roleEnum);
                    roleRepository.save(new Role(roleEnum));
                } else if (roles.size() == 1) {
                    log.info("Role already exists: {}", roleEnum);
                } else {
                    log.warn("Multiple roles found for name: {}. Consider cleaning up duplicates.", roleEnum);
                    // 可选择抛出异常：throw new IllegalStateException("Multiple roles found for name: " + roleEnum);
                }
            });

            // --- 2. 初始化管理员账户 ---
            String adminUsername = "admin";
            List<User> admins = userRepository.findByUsername(adminUsername);
            if (admins.isEmpty()) {
                log.info("Creating default admin user: {}", adminUsername);
                User adminUser = new User();
                adminUser.setUsername(adminUsername);
                adminUser.setPassword(passwordEncoder.encode(adminPassword));
                adminUser.setPhone("10086");
                adminUser.setEnabled(true);

                // 赋予所有角色
                Set<Role> roles = new HashSet<>(roleRepository.findAll());
                adminUser.setRoles(roles);

                userRepository.save(adminUser);
                log.info("Default admin user created successfully: {}", adminUsername);
            } else if (admins.size() == 1) {
                log.info("Admin user already exists: {}", adminUsername);
            } else {
                log.warn("Multiple admin users found for username: {}. Consider cleaning up duplicates.", adminUsername);
                // 可选择抛出异常：throw new IllegalStateException("Multiple admins found for username: " + adminUsername);
            }
        };
    }
}